package com.bee.web.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.bee.web.mapper.ServiceAreaEntityMapper;
import com.bee.web.util.DateUtil;
import com.bee.web.util.Page;
import com.bee.web.util.StringUtil;
import com.bee.web.vo.bean.AreaBean;
import com.hengyuan.db.ServiceAreaEntity;

/**
 * @author liuzy
 * @version 2015年6月13日
 */
@Service
public class ServiceAreaService {
	
    @Autowired
    private ServiceAreaEntityMapper serviceAreaEntityMapper;
    
    public int searchCount(AreaBean bean, Page page) {
    	ServiceAreaEntity entity = new ServiceAreaEntity();
    	entity.setAreaId(bean.getAreaId());
    	entity.setAreaName(bean.getAreaName());
    	return serviceAreaEntityMapper.searchCount(entity, page);
    }

    public List<AreaBean> searchList(AreaBean bean, Page page) throws Exception {
    	ServiceAreaEntity entity = new ServiceAreaEntity();
    	entity.setAreaId(bean.getAreaId());
    	entity.setAreaName(bean.getAreaName());
    	List<ServiceAreaEntity> list = serviceAreaEntityMapper.searchList(entity, page);
        List<AreaBean> beans = new ArrayList<>();
        for (ServiceAreaEntity e : list) {
            AreaBean b = new AreaBean();
            b.setAreaId(e.getAreaId());
            b.setAreaName(e.getAreaName());
            b.setStatus(e.getStatus());
            b.setCreateTime(DateUtil.format(e.getCreateTime()));
            b.setUpdateTime(DateUtil.format(e.getUpdateTime()));
            beans.add(b);
        }
        return beans;
    }

    public boolean switchStatus(String areaId, String status) throws Exception {
    	ServiceAreaEntity entity = new ServiceAreaEntity();
    	entity.setAreaId(areaId);
        if ("Y".equals(status)) {
        	entity.setStatus("N");
        } else if ("N".equals(status)) {
        	entity.setStatus("Y");
        }
        if (serviceAreaEntityMapper.update(entity) > 0) {
			return true;
		} else {
			return false;
		}
    }

	public boolean delete(String areaId) throws Exception {
		if (serviceAreaEntityMapper.delete(areaId) > 0) {
			return true;
		} else {
			return false;
		}
	}

	public boolean saveOrUpdate(AreaBean bean) {
		if (bean != null && !StringUtil.isNullOrEmpty(bean.getAreaId())) {
			ServiceAreaEntity e = new ServiceAreaEntity();
			e.setAreaId(bean.getAreaId());
			e.setAreaName(bean.getAreaName());
			e.setStatus(bean.getStatus());
			int count = 0;
			if (isExists(bean.getAreaId())) {
				count = serviceAreaEntityMapper.update(e);
			} else {
				e.setStatus("Y");
				count = serviceAreaEntityMapper.insert(e);
			}
			if (count > 0) {
				return true;
			}
		}
		return false;
	}

	public boolean isExists(String areaId) {
		ServiceAreaEntity entity = serviceAreaEntityMapper.selectById(areaId);
		if (entity == null) {
			return false;
		} else {
			return true;
		}
	}
	
}
